/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package doc2db.interfaces.action;

import doc2db.DbManager.DbSelects;
import doc2db.Keey;
import doc2db.UserProp;
import doc2db.interfaces.mainWindow.MyFrame;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Properties;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *
 * @author yuriy
 */
public class CreateConectionAction implements ActionListener{
    private boolean needUser ;
    private MyFrame mf;

    public CreateConectionAction(MyFrame m, boolean neededEnterUserParam){
        mf = m;
        needUser = neededEnterUserParam;
    }
    

    public void actionPerformed(ActionEvent e) {
        Authentication a = new Authentication(null);
        a.setVisible(true);
    }

    class Authentication extends JDialog {
        private final String port = "5432";

        private Font s;//= new Font("monospaced", Font.PLAIN, 12);
        private JTextField jTextFielddbhost = new JTextField(UserProp.dbHost);
        private JTextField jTextFielddbname = new JTextField(UserProp.dbName);
        private JTextField jTextFielddbuser = new JTextField(UserProp.user);
        private JPasswordField jTextFielddbpswd = new JPasswordField(UserProp.pswd);
        private JLabel jLabelDbhost = new JLabel("Ip адрес узла БД :");
        private JLabel jLabelDbname = new JLabel("Имя БД :");
        private JLabel jLabelDbuser = new JLabel("Имя пользователя :");
        private JLabel jLabelDbpswd = new JLabel("Пароль пользователя :");
        private JButton jButton1 = new JButton("OK");
        private Dimension mySize = new Dimension(240, 400);

        public Authentication(Frame f) {
            super(f, "DB", true);
            s = UserProp.paneFont;
            if(!needUser){
                mySize = new Dimension(240, 300);
                jLabelDbuser.setVisible(false);
                jLabelDbpswd.setVisible(false);
                jTextFielddbuser.setVisible(false);
                jTextFielddbpswd.setVisible(false);
            }
            this.initComponents();
        }

        /**
         * инициализирует компоненты
         * init all component
         */
        private void initComponents(){
            FramePropertis();
            Container contentPane = getContentPane();
            JPanel jPanel1 = new JPanel();
            jPanel1 = this.intiVariable();
            contentPane.add(jPanel1);
            setSize(mySize);
            Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension screnSize = kit.getScreenSize();
            int screanHeight = screnSize.height;
            int screanWidth = screnSize.width;
            setLocation(screanWidth / 2 - mySize.width / 2, screanHeight / 2 - mySize.height / 2);
        }

        /**
         * создаёт окно по середине экрана с параметрами 255:330
         * create window in center of scren with paraneters 255:330
         *
         * @throws java.awt.HeadlessException
         */
        private void FramePropertis(){
            setTitle("соеденение с БД");
            setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            setResizable(true);
        }

        /**
         *
         * @return
         * @throws java.awt.HeadlessException
         * @throws java.io.IOException
         */
        private JPanel intiVariable() {
            this.setMyFont();
            JPanel jPanel1 = this.setVariablePosition();
            ActionListener al = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    StringBuffer url = new StringBuffer();
                    url.append("jdbc:postgresql://").append(jTextFielddbhost.getText())
                            .append(":").append(port).append("/").append(jTextFielddbname.getText());
                    Properties p = new Properties();
                    String pasStr = new String(jTextFielddbpswd.getPassword());
                    //jTextFielddbpswd.getText();
                    p = getProperties(jTextFielddbuser.getText(),pasStr);
                    setVisible(false);
                    if(isConnected(url.toString(), p)){
                        JOptionPane.showMessageDialog(null, "Соеденение подтвержденно",
                                "message", JOptionPane.DEFAULT_OPTION);
                        Keey.isConnected = true;
                        UserProp.dbHost = jTextFielddbhost.getText();
                        UserProp.dbName = jTextFielddbname.getText();
                        UserProp.userInDb = jTextFielddbuser.getText();
                        UserProp.pswdInDb = pasStr;
                        mf.toolBar.setEnableButton(true);
                        mf.menu.setEnableButton(true);
                    }else{
                        JOptionPane.showMessageDialog(null, "Соеденение отвергнуто",
                                "error! ",JOptionPane.ERROR_MESSAGE);
                        setVisible(true);
                    }
                }
            };
            jButton1.addActionListener(al);
            jTextFielddbhost.addActionListener(al);
            jTextFielddbname.addActionListener(al);
            jTextFielddbuser.addActionListener(al);
            jTextFielddbpswd.addActionListener(al);
            jButton1.setPreferredSize(new Dimension(60, 35));
            return jPanel1;
        }

        private void setMyFont() {
            jLabelDbhost.setFont(s);
            jLabelDbname.setFont(s);
            jLabelDbuser.setFont(s);
            jLabelDbpswd.setFont(s);
            jTextFielddbhost.setFont(s);
            jTextFielddbname.setFont(s);
            jTextFielddbuser.setFont(s);
            jTextFielddbpswd.setFont(s);
            jButton1.setFont(s);
        }

        private JPanel setVariablePosition() {
            JPanel jPanel1 = new JPanel(new BorderLayout());
            int size = 20;
            jTextFielddbhost.setColumns(size);
            jTextFielddbhost.setMaximumSize(jTextFielddbhost.getPreferredSize());
            jTextFielddbname.setColumns(size);
            jTextFielddbname.setMaximumSize(jTextFielddbname.getPreferredSize());
            jTextFielddbuser.setColumns(size);
            jTextFielddbuser.setMaximumSize(jTextFielddbuser.getPreferredSize());
            jTextFielddbpswd.setColumns(size);
            jTextFielddbpswd.setMaximumSize(jTextFielddbpswd.getPreferredSize());

            Box hb[] = new Box[14];

            hb[0] = Box.createHorizontalBox();

            hb[2] = Box.createHorizontalBox();
            hb[2].add(Box.createGlue());
            hb[2].add(jLabelDbhost);
            hb[2].add(Box.createGlue());

            hb[3] = Box.createHorizontalBox();
            hb[3].add(Box.createGlue());
            hb[3].add(jTextFielddbhost);
            hb[3].add(Box.createGlue());

            hb[4] = Box.createHorizontalBox();
            hb[4].add(Box.createGlue());
            hb[4].add(jLabelDbname);
            hb[4].add(Box.createGlue());

            hb[5] = Box.createHorizontalBox();
            hb[5].add(Box.createGlue());
            hb[5].add(jTextFielddbname);
            hb[5].add(Box.createGlue());

            hb[6] = Box.createHorizontalBox();
            hb[6].add(Box.createGlue());
            hb[6].add(jLabelDbuser);
            hb[6].add(Box.createGlue());

            hb[7] = Box.createHorizontalBox();
            hb[7].add(Box.createGlue());
            hb[7].add(jTextFielddbuser);
            hb[7].add(Box.createGlue());

            hb[8] = Box.createHorizontalBox();
            hb[8].add(Box.createGlue());
            hb[8].add(jLabelDbpswd);
            hb[8].add(Box.createGlue());

            hb[9] = Box.createHorizontalBox();
            hb[9].add(Box.createGlue());
            hb[9].add(jTextFielddbpswd);
            hb[9].add(Box.createGlue());

            Box V = Box.createVerticalBox();
            for (int i = 2; i < 10; i++) {
                V.add(Box.createVerticalStrut(3));
                V.add(hb[i]);
            }
            V.add(Box.createGlue());

            jPanel1.add(V, BorderLayout.CENTER);

            Box hbOk = Box.createHorizontalBox();
            hbOk.add(Box.createGlue());
            hbOk.add(jButton1);
            hbOk.add(Box.createHorizontalStrut(10));
            jPanel1.add(hbOk, BorderLayout.SOUTH);

            mySize.height = jPanel1.getPreferredSize().height + 10 + jButton1.getPreferredSize().height;
            mySize.width = jPanel1.getPreferredSize().width + 10;


            return jPanel1;
        }
    }
    
    private   boolean isConnected(String dbURL, Properties properties) /*throws Exception*/{
        boolean ret = false;
        try {
            DbSelects dBManager = new DbSelects(dbURL, properties);
            ret = dBManager.isConnected();
            dBManager.close_connect();
        } catch (SQLException e) {
            System.err.println(e);
        } catch (ClassNotFoundException e) {
            System.err.println(e);
        }
        return ret;
    }

    private Properties getProperties(String n, String p) {
        Properties props = new Properties();
        props.setProperty("user", n);
        props.setProperty("password", p);
        return props;
    }
}
